<?php

namespace app\admin\controller\order;

use app\admin\model\Bin;
use app\admin\model\bin\Allot as BinAllot;
use app\admin\model\bin\History;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 调拨订单
 *
 * @icon fa fa-circle-o
 */
class Allot extends Backend
{

    /**
     * Allot模型对象
     * @var \app\admin\model\order\Allot
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Allot;
        $this->view->assign("binTypeList", $this->model->getBinTypeList());
        $this->view->assign("binOriginList", $this->model->getBinOriginList());
        $this->view->assign("currencyTypeList", $this->model->getCurrencyTypeList());
        $this->view->assign("yardList", $this->model->yardList());

    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with([
                'type'=>function($query){$query->withField('name');},
                'trafficunit'=>function($query){$query->withField('organ_name');},
                'takeyard'=>function($query){$query->withField('organ_name');},
                'aimyard'=>function($query){$query->withField('organ_name');},
                'admin'=>function($query){$query->withField('nickname');},
            ])
            ->where($where)
            ->order(['createtime'=>'desc'])
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }



    /**
     *调拨出库
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            /*            $yardList=Organization::getYard();*/
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['createtime']=time();
        $params['allotouttime']=time();
        $params['allottime']=strtotime($params['allottime']);
        $params['allot_sn']='AL'.substr(md5(microtime(true)), 0, 9);
        $params['allot_number']=count($params['multiplejson']);
        $binData=$params['multiplejson'];
        $binIds=[];
        $binHistoty=[];
        unset($params['multiplejson']);
        unset($params['choose_bin']);
        $bin=new Bin();
        $result = false;
        Db::startTrans();
        try {

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->insertGetId($params);

            /* foreach ($binIds as $item){
                $result= $bin->save([
                     'current_status'  => 3,
                 ],['id' => $item]);
             }*/

            foreach ($binData as $k=> &$vo){
                $vo=array_merge($params,$vo);
                $vo['bin_sn']=$bin->where(['id'=>$vo['bin_id']])->value('bin_sn');
                $vo['bin_origin']=$bin->where(['id'=>$vo['bin_id']])->value('bin_origin');
                $vo['bin_native']=$bin->where(['id'=>$vo['bin_id']])->value('bin_native');
                $vo['allot_order_id']=$result;
                $vo['allotouttime']=time();
                if(!empty($vo['take_null_time'])){
                    $vo['take_null_time']=strtotime($vo['take_null_time']);
                    $binHistoty[$k]['take_null_time']=$vo['take_null_time'];
                }
                $vo['current_status']=1;
                $binIds[$k]['id']=$vo['bin_id'];
                $binIds[$k]['yard_id']=$vo['aim_yard_id'];
                $binIds[$k]['current_status']=2;
                $binIds[$k]['last_status']=4;


                $binHistoty[$k]['bin_id']=$vo['bin_id'];
                $binHistoty[$k]['business_type']=4;
                $binHistoty[$k]['receipt']=$vo['allot_sn'];
                $binHistoty[$k]['organization_id']=$vo['traffic_unit'];
                $binHistoty[$k]['organ_type']=6;
                $binHistoty[$k]['yard_id']=$vo['take_yard_id'];
                $binHistoty[$k]['createtime']=time();
                unset($vo['remark']);
            }
            $binAllot=new BinAllot();
            $res= $binAllot->allowField(true)->saveAll($binData);
            $result= $bin->allowField(true)->isUpdate()->saveAll($binIds);
            $history=new History();
            $historyRes= $history->allowField(true)->saveAll($binHistoty);

            Db::commit();

        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    /**
     * 调拨入库
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function to_edit($ids = null)
    {
        $row = $this->model->get($ids);
        $binAllotLists= db('bin_allot')->where(['allot_order_id'=>$ids])->select();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('binAllotLists', $binAllotLists);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $binHistoty=[];
        $allotinParams['allotintime']=strtotime($params['allotintime']);
        $allotinParams['entertyardtime']=strtotime($params['entertyardtime']);
        $allotinParams['current_status']=2;
        $bin=new Bin();
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($allotinParams);
            foreach ($binAllotLists as $k=> &$vo){
                $vo=array_merge($vo,$allotinParams);

                $binIds[$k]['id']=$vo['bin_id'];
                $binIds[$k]['current_status']=1;
                $binIds[$k]['last_status']=5;

                $binHistoty[$k]['bin_id']=$vo['bin_id'];
                $binHistoty[$k]['business_type']=5;
                $binHistoty[$k]['receipt']=$this->model->where(['id'=>$ids])->value('allot_sn');
                $binHistoty[$k]['organization_id']=$vo['traffic_unit'];
                $binHistoty[$k]['organ_type']=6;
                $binHistoty[$k]['yard_id']=$params['aim_yard_id'];
                $binHistoty[$k]['createtime']=time();
                $binHistoty[$k]['entertime']=$allotinParams['entertyardtime'];
            }
            $binAllot=new BinAllot();
            $res= $binAllot->allowField(true)->saveAll($binAllotLists);
            $result= $bin->allowField(true)->isUpdate()->saveAll($binIds);
            $history=new History();
            $historyRes= $history->allowField(true)->saveAll($binHistoty);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
